package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Order(0)  //主要是设置其拦截顺序
@WebFilter(value = "wmTokenFilter",urlPatterns = "/*")
@Slf4j
@Component
public class WmTokenFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
         //1.获取请求对象
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        //2.获取请求头中的userId
        String userId = request.getHeader("userId");
        //3.如果存在userId,将userId设置到Threadlocal中
        if (StringUtils.isNotBlank(userId)) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);//使用工具类将请求头中的userId存放于Threadlocal中
            log.info("自媒体用户登录成功userId==>"+userId);
        }
        //4.放行请求
        filterChain.doFilter(servletRequest,servletResponse);
        //清除当前登录用户
        WmThreadLocalUtils.clear();
    }
}
